package com.xiongjie.micro;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.healthchecks.HealthCheckHandler;
import io.vertx.ext.healthchecks.HealthChecks;
import io.vertx.ext.healthchecks.Status;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.servicediscovery.ServiceDiscovery;
import io.vertx.servicediscovery.types.HttpEndpoint;

public class ServiceDiscoveryHealthChecks extends AbstractVerticle {

    private ServiceDiscovery discovery;

    @Override
    public void start() {
        HealthCheckHandler healthCheckHandler2 = HealthCheckHandler.createWithHealthChecks(HealthChecks.create(vertx));
        healthCheckHandler2.register("hello check", future -> HttpEndpoint.getClient(discovery, (rec) -> "hello".equals(rec.getName()), client -> {
                            if (client.failed()) {
                                future.fail(client.cause());
                                System.out.println("失败");
                            } else {
                                client.result().close();
                                System.out.println("成功");
                                future.complete(Status.OK());
                            }
                        })
        );
        Router router = Router.router(vertx);
        router.get("/hello").handler(this::hello);
        router.get("/").handler(healthCheckHandler2);

        vertx.createHttpServer()
                .requestHandler(router)
                .listen(8080,listen ->{
                    if (listen.succeeded()) {
                        discovery = ServiceDiscovery.create(vertx);
                        discovery.publish(HttpEndpoint.createRecord("hello", "localhost", 8080,"/hello"), publish -> {
                            if (publish.succeeded()) {
                                System.out.println("发布服务成功");
                            } else {
                                System.out.println("发布服务失败");
                            }
                        });
                    } else {
                        System.out.println("失败");
                    }
                });
    }

    //这是路由处理器，决定http请求来后怎么返回页面内容
    private void hello(RoutingContext rc) {
        String message = "hello";
        if (rc.pathParam("name") != null) {
            message += " " + rc.pathParam("name");
        }
        JsonObject json = new JsonObject().put("message", message);
        rc.response()
                .putHeader(HttpHeaders.CONTENT_TYPE, "application/json")
                .end(json.encode());
    }
}
